import { ModelType } from '@/common-typings';

import { getCommunicationData } from './service';

const CODE = {
  SUCCESS: 1,
  FAIL: 2,
};

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const cbForRes = (fn: any = () => {}, res: any = {}) => {
  if (fn) {
    fn(res);
  }
};

const Model: ModelType = {
  namespace: 'communicationRecord',
  state: {
    // 表格区域的数据
    tableData: {
      // 主页表格数据
      list: [],
      total: 0,
      pageSize: 10,
      currentPage: 1,
    },
    // 表单区域的数据
    formData: {
      // 查询条件
      inquiryCondition: {},
    },
  },
  // effects里有三个参数， put用于触发action，(put类似于dispatch,此处action跟redux的action一样)
  // call用于调用异步逻辑, fn是异步操作以后执行的回调。
  effects: {
    // 查询用户风险名单
    *getUserCommunicationDataEffect({ payload, fn }, { call, put }) {
      const res = yield call(getCommunicationData, payload);
      if (res && res.code === CODE.SUCCESS) {
        if (res.data && res.data) {
          yield put({ type: 'setCommunicationData', payload: res.data });
        }
        cbForRes(fn, res);
      }
    },
  },
  reducers: {
    // 保存查询后的手机邮箱数据
    setCommunicationData(state, { payload }) {
      const newState = Object.assign({}, state);
      newState.tableData.list = payload.list;
      newState.tableData.total = payload.total;
      return newState;
    },
    // 点击翻页修改表格每一页显示页码
    setPageSize(state, { payload }) {
      const newState = Object.assign({}, state);
      const { pageSize, currentPage } = payload;
      if (pageSize) newState.tableData.pageSize = pageSize;
      if (currentPage) newState.tableData.currentPage = currentPage;
      return newState;
    },
    // 保存查询时候表单区的状态、 查询条件、细分类型的子项
    setFormAreaInfo(state, { payload }) {
      const newState = Object.assign({}, state);
      newState.formData.inquiryCondition = payload;
      return newState;
    },
  },
};

export default Model;
